package com.dev.op.controller;

import com.dev.op.VO.LoginInfoVO;
import com.dev.op.VO.LoginTryVO;
import com.dev.op.VO.ResultVO;
import com.dev.op.config.CostumeProperties;
import com.dev.op.entity.User;
import com.dev.op.entity.UserRole;
import com.dev.op.enums.ResultCode;
import com.dev.op.exceptions.BizException;
import com.dev.op.service.UserRoleService;
import com.dev.op.service.UserService;
import com.dev.op.util.JWTUtil;
import com.dev.op.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CostumeProperties costumeProperties;

    @PostMapping("/login")
    public ResultVO<LoginInfoVO> login(@RequestBody LoginTryVO loginTryVO) {
        try {
            //验证用户
            User user = userService.login(loginTryVO.getPhoneOrEmail(), loginTryVO.getPassword());
            if (user == null) {
                return ResultVO.error(ResultCode.UNAUTHORIZED.code(), "用户不存在或密码错误");
            }
            //从数据库中获取角色
            List<UserRole> userRoles = userRoleService.getUserRolesByUserId(user.getId());
            //生成 token
            String token = jwtUtil.getJWT(user, userRoles);
            //Redis区
            //保存 tokenRedis
            //根据 yml配置过期时间
            redisUtil.saveToken((token),Long.parseLong( costumeProperties.getRedis().getLoginExpireTime()));
            //保存 用户的
            //返回登录信息
            return ResultVO.success(new LoginInfoVO(token, user, userRoles));
        } catch (RuntimeException e) {
            throw new BizException(ResultCode.SYSTEM_ERROR.code(), "系统异常");
        }
    }


    @GetMapping("/logoff")
    public ResultVO<Boolean> logoff(HttpServletRequest request) {
        //登出的逻辑: 使得redis中的token失效
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")){
            String token = authHeader.substring(7);
            redisUtil.deleteToken(token);
            return ResultVO.success(true);
        }
        else{
            return ResultVO.success(false);
        }
    }


    @PostMapping("/register")
    @Transactional
    public ResultVO<User> register(@RequestBody User user) {
        try {
            userService.save(user);
            List<String> roles = new ArrayList<>();
            roles.add("student");
            userRoleService.grantUserRolesByRolesName(user.getId(),roles);
            return ResultVO.success(user);
        }
        catch (Exception e) {
            return ResultVO.error(ResultCode.PARAM_ERROR.message());
        }
    }


}
